package at.bartinger.snake;

import java.util.LinkedList;


public class Snake {

	private final int SNK_E_RADIUS = 3;


	private int bH;
	private int bW;


	private int speed;

	private LinkedList<SnakeElement> snake;


	
	public Snake(int speed,int displayHeight, int displayWidth){
		bH= displayHeight;
		bW= displayWidth;
		this.snake = new LinkedList<SnakeElement>();
		this.speed = speed;

		addNewElementAt(100,100);
		for(int i =0; i<2;i++){
			addNewElement();
		}
	}

	public void addNewElementAt(float x, float y){
		snake.add(new SnakeElement(x,y,SNK_E_RADIUS));
	}

	public void addNewElement(){
		snake.add(
				new SnakeElement(
						snake.get(snake.size()-1).x,
						snake.get(snake.size()-1).y,
						SNK_E_RADIUS)
				);
	}

	public LinkedList<SnakeElement> getSnake(){
		return this.snake;
	}

	public void move(double vx, double vy){
		vx*=speed;
		vy*=speed;
	
		snake.addFirst(new SnakeElement(snake.get(0).x+vx,snake.get(0).y+vy,SNK_E_RADIUS));
		snake.removeLast();
	}


	public boolean selfHit(){
		if(snake.size() > 1){
			for(SnakeElement e : snake){
				if(!snake.get(0).equals(e)){
					if(testCircleCollision(snake.get(0).x,snake.get(0).y,snake.get(0).radius,e.x,e.y,e.radius)) return true;
				}
				
			}
		}
		return false;

	}


	public static boolean testCircleCollision(double x1, double y1, double r1, double x2, double y2, double r2) {
		double difX = x2 - x1;
		double difY = y2 - y1;
		double distance = Math.sqrt(difX*difX + difY*difY);
		return distance < (r1 + r2);
	}
	
	public boolean headhitBonus(SnakeElement bonus){
		SnakeElement head = snake.get(0);
		return testCircleCollision(head.x,head.y,head.radius,bonus.x,bonus.y,bonus.radius);
	}
	


	public void wallHit(){
		if(snake.get(0).y < 0)
			snake.get(0).y=bH;
		else if(snake.get(0).y > bH)
			snake.get(0).y=0;
		else if(snake.get(0).x < 0)
			snake.get(0).x=bW;
		else if(snake.get(0).x > bW)
			snake.get(0).x=0;

	}
	
	


}
